package com.motu.vertx.module.utility.toolset;

import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public class ErrorWordManager {
	public static final Logger logger = LoggerFactory.getLogger(ErrorWord.class);


	private static ConcurrentHashMap<String, JsonObject> wordList = new ConcurrentHashMap<String, JsonObject>();

	public static String get(String cmd, ErrorWord er, int language) {
		String key = "";
		if (er != null) {
			String enumName = er.name();
			key = cmd + "_" + enumName;
			if (wordList.containsKey(key)) {
				JsonObject obj = wordList.get(key);
				String word = obj.getString("des_" + language);
				if (word == null) {
					word = obj.getString("des_1");
				}
				return word;
			} else {//取通用的错误码
				String defKey = "CMD_DEFAULT" + "_" + er.name();
				if (wordList.containsKey(defKey)) {
					JsonObject obj = wordList.get(defKey);
					String word = obj.getString("des_" + language);
					if (word == null) {
						word = obj.getString("des_1");
					}
					return word;
				}
			}
		}
//		System.out.println("errorWord get key:"+key);
		return "error word :" + key;
	}

	public static String get(ErrorWord er) {
		return get("CMD_DEFAULT", er, 0);
	}

	public static void init() {
		if (MysqlClient.getProjectPool() == null) {
			return;
		}
		initWords();
	}

	public static void initWords() {
		logger.info("ErrorWord.init start...");
		long startTime = System.currentTimeMillis();
		String sql = "select * from errwords;";
		MysqlTool.queryJsonArrayFromDb(MysqlClient.getProjectPool(), sql, new JsonArray(), handler -> {
			if (handler.succeeded()) {
				JsonArray list = handler.result();
				ConcurrentHashMap<String, JsonObject> tmp = new ConcurrentHashMap<String, JsonObject>();
				for (int i = 0; i < list.size(); i++) {
					JsonObject obj = list.getJsonObject(i);
					String cmd = obj.getString("cmd").trim();//去掉空格，以免配错很难发现
					String code = obj.getString("errcode").trim();//去掉空格
					tmp.put(cmd + "_" + code, obj);
					//					System.out.println("errorWord key:"+(cmd+"_"+code)+" obj:"+obj);
				}
				logger.info("ErrorWord.init size:" + tmp.size() + " runTime:" + (System.currentTimeMillis() - startTime) + "ms");
				wordList.clear();
				wordList = tmp;
			} else {
				logger.error("ErrorWord.init failed! reason:" + handler.cause().getMessage() + " runTime:" + (System.currentTimeMillis() - startTime) + "ms");
			}
		});
	}
}
